/**
 * 右键菜单动作处理 Composable
 * 处理复制、删除、引用、转发、多选等动作
 * @author LYC
 * @date 2025-09-13
 */

import type { Message } from '@/store/chat/type'
import { useChatStore } from '@/store/chat'
import { useGlobalMessageSelection } from './useMessageSelection'
import { formatDetailTime } from '@/utils/dateUtils'
import {
  Copy,
  MessageSquareQuote,
  Share,
  CheckSquare,
  Trash2,
  X,
  CheckCheck
} from 'lucide-vue-next'

/**
 * 剪贴板操作
 */
export const useClipboard = (): { copyToClipboard: (text: string) => Promise<boolean> } => {
  /**
   * 复制文本到剪贴板
   */
  const copyToClipboard = async (text: string): Promise<boolean> => {
    try {
      // 优先使用现代 Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(text)
        return true
      }

      // 降级方案：使用 execCommand
      return fallbackCopy(text)
    } catch (error) {
      console.error('Failed to copy to clipboard:', error)
      return fallbackCopy(text)
    }
  }

  /**
   * 降级复制方案
   */
  const fallbackCopy = (text: string): boolean => {
    try {
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      const result = document.execCommand('copy')
      document.body.removeChild(textArea)
      return result
    } catch (error) {
      console.error('Fallback copy failed:', error)
      return false
    }
  }

  return {
    copyToClipboard
  }
}

/**
 * 消息操作
 */
export const useMessageActions = (): {
  copyMessage: (message: Message) => Promise<void>
  copyMultipleMessages: (messages: Message[]) => Promise<void>
  deleteMessage: (message: Message) => Promise<void>
  deleteMultipleMessages: (messages: Message[]) => Promise<void>
  quoteMessage: (message: Message) => void
} => {
  const chatStore = useChatStore()
  const messageSelection = useGlobalMessageSelection()
  const { copyToClipboard } = useClipboard()

  /**
   * 复制消息内容
   */
  const copyMessage = async (message: Message): Promise<void> => {
    const success = await copyToClipboard(message.content)
    if (success) {
      showToast('消息已复制')
    } else {
      showToast('复制失败', 'error')
    }
  }

  /**
   * 复制多个消息内容
   */
  const copyMultipleMessages = async (messages: Message[]): Promise<void> => {
    const content = messages
      .map((msg) => `${formatDetailTime(msg.timestamp)}: ${msg.content}`)
      .join('\n')

    const success = await copyToClipboard(content)
    if (success) {
      showToast(`已复制 ${messages.length} 条消息`)
    } else {
      showToast('复制失败', 'error')
    }
  }

  /**
   * 删除消息
   */
  const deleteMessage = async (message: Message): Promise<void> => {
    try {
      // TODO: 实现删除消息的API调用
      console.log('删除消息:', message.id)
      showToast('消息已删除')
    } catch (error) {
      console.error('删除消息失败:', error)
      showToast('删除失败', 'error')
    }
  }

  /**
   * 批量删除消息
   */
  const deleteMultipleMessages = async (messages: Message[]): Promise<void> => {
    try {
      // TODO: 实现批量删除消息的API调用
      console.log(
        '批量删除消息:',
        messages.map((m) => m.id)
      )
      showToast(`已删除 ${messages.length} 条消息`)
      messageSelection.clearSelection()
    } catch (error) {
      console.error('批量删除消息失败:', error)
      showToast('删除失败', 'error')
    }
  }

  /**
   * 引用回复消息
   */
  const quoteMessage = (message: Message): void => {
    try {
      // TODO: 实现引用回复功能
      const quotedText = `> ${message.content}\n\n`
      // 将引用文本插入到输入框
      insertQuoteToInput(quotedText)
      showToast('已引用消息')
    } catch (error) {
      console.error('引用消息失败:', error)
      showToast('引用失败', 'error')
    }
  }

  /**
   * 转发消息
   */
  const forwardMessage = (message: Message): void => {
    try {
      // TODO: 实现转发消息功能
      console.log('转发消息:', message.id)
      showForwardDialog(message)
    } catch (error) {
      console.error('转发消息失败:', error)
      showToast('转发失败', 'error')
    }
  }

  /**
   * 批量转发消息
   */
  const forwardMultipleMessages = (messages: Message[]): void => {
    try {
      console.log(
        '批量转发消息:',
        messages.map((m) => m.id)
      )
      showForwardDialog(messages)
    } catch (error) {
      console.error('批量转发失败:', error)
      showToast('转发失败', 'error')
    }
  }

  /**
   * 进入多选模式
   */
  const enterMultiSelectMode = (message: Message): void => {
    messageSelection.enterMultiSelectMode(message.id)
    showToast('已进入多选模式')
  }

  /**
   * 退出多选模式
   */
  const exitMultiSelectMode = (): void => {
    messageSelection.exitMultiSelectMode()
    showToast('已退出多选模式')
  }

  /**
   * 全选消息
   */
  const selectAllMessages = (): void => {
    const messages = chatStore.currentMessages
    messageSelection.selectAllMessages(messages)
    showToast(`已选择 ${messages.length} 条消息`)
  }

  return {
    copyMessage,
    copyMultipleMessages,
    deleteMessage,
    deleteMultipleMessages,
    quoteMessage,
    forwardMessage,
    forwardMultipleMessages,
    enterMultiSelectMode,
    exitMultiSelectMode,
    selectAllMessages
  }
}

/**
 * 辅助函数
 */

// 时间格式化函数已移至 utils/dateUtils.ts

/**
 * 显示提示消息
 */
const showToast = (message: string, type: 'success' | 'error' | 'info' = 'success'): void => {
  // TODO: 实现Toast组件
  console.log(`[${type.toUpperCase()}] ${message}`)
}

/**
 * 将引用文本插入到输入框
 */
const insertQuoteToInput = (quotedText: string): void => {
  // TODO: 实现插入引用文本到输入框
  console.log('插入引用文本:', quotedText)
}

/**
 * 显示转发对话框
 */
const showForwardDialog = (messages: Message | Message[]): void => {
  // TODO: 实现转发对话框
  console.log('显示转发对话框:', messages)
}

/**
 * 右键菜单动作配置
 */
export const useContextMenuActions = (): void => {
  const messageActions = useMessageActions()
  const messageSelection = useGlobalMessageSelection()

  /**
   * 获取单个消息的菜单动作
   */
  const getSingleMessageActions = (message: Message) => [
    {
      id: 'copy',
      label: '复制',
      icon: Copy,
      shortcut: 'Ctrl+C',
      action: () => messageActions.copyMessage(message)
    },
    {
      id: 'quote',
      label: '引用',
      icon: MessageSquareQuote,
      action: () => messageActions.quoteMessage(message)
    },
    {
      id: 'forward',
      label: '转发',
      icon: Share,
      action: () => messageActions.forwardMessage(message)
    },
    {
      id: 'divider1',
      divider: true,
      label: '',
      action: () => {}
    },
    {
      id: 'multiselect',
      label: '多选',
      icon: CheckSquare,
      action: () => messageActions.enterMultiSelectMode(message)
    },
    {
      id: 'divider2',
      divider: true,
      label: '',
      action: () => {}
    },
    {
      id: 'delete',
      label: '删除',
      icon: Trash2,
      shortcut: 'Delete',
      action: () => messageActions.deleteMessage(message)
    }
  ]

  /**
   * 获取多选模式的菜单动作
   */
  const getMultiSelectActions = (messages: Message[]) => [
    {
      id: 'copy-multiple',
      label: `复制 ${messages.length} 条消息`,
      icon: Copy,
      action: () => messageActions.copyMultipleMessages(messages)
    },
    {
      id: 'forward-multiple',
      label: `转发 ${messages.length} 条消息`,
      icon: Share,
      action: () => messageActions.forwardMultipleMessages(messages)
    },
    {
      id: 'divider1',
      divider: true,
      label: '',
      action: () => {}
    },
    {
      id: 'select-all',
      label: '全选',
      icon: CheckCheck,
      shortcut: 'Ctrl+A',
      action: () => messageActions.selectAllMessages()
    },
    {
      id: 'exit-multiselect',
      label: '退出多选',
      icon: X,
      shortcut: 'Esc',
      action: () => messageActions.exitMultiSelectMode()
    },
    {
      id: 'divider2',
      divider: true,
      label: '',
      action: () => {}
    },
    {
      id: 'delete-multiple',
      label: `删除 ${messages.length} 条消息`,
      icon: Trash2,
      shortcut: 'Delete',
      action: () => messageActions.deleteMultipleMessages(messages)
    }
  ]

  /**
   * 获取当前上下文的菜单动作
   */
  const getContextMenuActions = (message: Message) => {
    if (messageSelection.state.isMultiSelectMode) {
      const selectedMessages = messageSelection.getSelectedMessages([message])
      return getMultiSelectActions(selectedMessages)
    }
    return getSingleMessageActions(message)
  }

  return {
    getSingleMessageActions,
    getMultiSelectActions,
    getContextMenuActions,
    ...messageActions
  }
}
